<template>
  <div class="medicines-manage">
    <div class="page-header">
      <h2>药品管理</h2>
      <el-button type="primary" @click="() => { resetForm(); dialogVisible = true; }">
        <el-icon><Plus /></el-icon>添加药品
      </el-button>
    </div>

    <el-table :data="medicines" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="药品名称" />
      <el-table-column prop="price" label="价格">
        <template #default="{ row }">
          ¥{{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">
            {{ row.status === 'active' ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑药品对话框 -->
    <el-dialog
      :title="form.id ? '编辑药品' : '添加药品'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="药品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" />
        </el-form-item>
        <el-form-item label="用法用量" prop="usage">
          <el-input type="textarea" v-model="form.usage" rows="2" />
        </el-form-item>
        <el-form-item label="图片链接" prop="image">
          <el-input v-model="form.image" placeholder="请输入药品图片URL" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'MedicinesManage',
  components: {
    Plus,
    Edit,
    Delete
  },
  setup() {
    const medicines = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const formRef = ref(null)

    const form = ref({
      id: '',
      name: '',
      price: 0,
      stock: 0,
      category: '',
      status: 'active',
      description: '',
      manufacturer: '',
      specification: '',
      usage: '',
      image: ''
    })

    const categories = [
      { value: '感冒药', label: '感冒药' },
      { value: '解热镇痛', label: '解热镇痛' },
      { value: '维生素', label: '维生素' },
      { value: '消炎药', label: '消炎药' },
      { value: '抗生素', label: '抗生素' },
      { value: '跌打损伤', label: '跌打损伤' },
      { value: '止咳药', label: '止咳药' }
    ]

    const rules = {
      name: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
      price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
      stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
      category: [{ required: true, message: '请选择分类', trigger: 'change' }],
      manufacturer: [{ required: true, message: '请输入生产厂家', trigger: 'blur' }],
      specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
      usage: [{ required: true, message: '请输入用法用量', trigger: 'blur' }]
    }

    const fetchMedicines = async () => {
      loading.value = true
      try {
        const response = await axios.get('http://localhost:3000/medicines')
        medicines.value = response.data
      } catch (error) {
        ElMessage.error('获取药品列表失败')
      } finally {
        loading.value = false
      }
    }

    const resetForm = () => {
      form.value = {
        id: '',
        name: '',
        price: 0,
        stock: 0,
        category: '',
        status: 'active',
        description: '',
        manufacturer: '',
        specification: '',
        usage: '',
        image: ''
      }
    }

    const handleEdit = (row) => {
      form.value = { ...row }
      dialogVisible.value = true
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确定要删除该药品吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await axios.delete(`http://localhost:3000/medicines/${row.id}`)
          ElMessage.success('删除成功')
          fetchMedicines()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        
        if (form.value.id) {
          await axios.put(`http://localhost:3000/medicines/${form.value.id}`, form.value)
          ElMessage.success('更新成功')
        } else {
          await axios.post('http://localhost:3000/medicines', form.value)
          ElMessage.success('添加成功')
        }
        
        dialogVisible.value = false
        fetchMedicines()
        formRef.value.resetFields()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }

    onMounted(() => {
      console.log('药品管理页面加载')
      fetchMedicines()
    })

    return {
      medicines,
      loading,
      dialogVisible,
      form,
      formRef,
      categories,
      rules,
      handleEdit,
      handleDelete,
      handleSubmit,
      resetForm
    }
  }
}
</script>

<style scoped>
.medicines-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style> 